<template>
  <div ref="pageComBox" class="NewCustomer page_wrapper">
    <div ref="otherBox">
      <Params ref="params" @search="newCustomerList" />

      <el-row type="flex" justify="space-between" class="mb-3">
        <el-col :xs="20">
          <el-button-group>
            <el-button
              type="primary"
              :size="formSize"
              :loading="assistLoading"
              :disabled="assistDisabled"
              @click="assistHandle"
              >协助</el-button
            >
            <el-button
              type="primary"
              :size="formSize"
              :disabled="assistDisabled"
              @click="cancleAssistHandle"
              >取消协助</el-button
            >
            <el-button
              type="primary"
              :size="formSize"
              @click="addCustomerHandle"
              >添加客户</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>
    </div>

    <el-table
      ref="multipleTable"
      :data="dataList"
      style="width: 100%"
      :row-class-name="$getTableClass"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      element-loading-text="加载中..."
      @sort-change="sortChange"
      :max-height="tableHeight"
      :key="tableHeight"
      v-tabscroll="$getTableHeight"
    >
      <el-table-column type="selection" width="55" fixed="left">
      </el-table-column>
      <el-table-column label="客户信息" width="140">
        <template slot-scope="{ row }">
          <tab-user :user="row" :list="dataList" v-if="row"></tab-user>
        </template>
      </el-table-column>
      <!-- <el-table-column label="姓名" :width="sortTdWidth" fixed="left">
        <template slot-scope="scope">
          <div @click="followUpHandle(scope.row)" class="underLine">{{scope.row.name}}</div>
        </template>
      </el-table-column>
      <el-table-column label="电话" :width="smallWidth">
        <template slot-scope="scope">
          <div @click="followUpHandle(scope.row)" class="underLine">{{scope.row.mobile}}</div>
        </template>
      </el-table-column>
      <el-table-column label="性别" :width="sortTdWidth">
        <template slot-scope="{row}">
          {{SEXTYPELIST[row.sex]}}
        </template>
      </el-table-column> -->
      <el-table-column prop="age" label="年龄" :width="sortTdWidth">
        <template slot-scope="{ row }">{{ row.age || "—" }}</template>
      </el-table-column>
      <!-- <el-table-column prop="city" label="城市" :width="sortTdWidth">
      </el-table-column> -->
      <el-table-column prop="media" label="媒体" :width="sortTdWidth">
        <template slot-scope="{ row }">{{ row.media || "—" }}</template>
      </el-table-column>
      <el-table-column label="进度" :width="sortTdWidth">
        <template slot-scope="{ row }">
          {{ showFollowProcess(row.progress) }}
        </template>
      </el-table-column>
      <el-table-column label="锁定状态" :width="80">
        <template slot-scope="{ row }">
          <el-tag
            type="danger"
            class="tab_el_tag"
            size="mini"
            v-if="row.lock == 1"
            >锁定</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="employee.name" label="持有人" :width="80">
        <template slot-scope="{ row }">{{ row.employee.name || "—" }}</template>
      </el-table-column>
      <!-- <el-table-column label="通话状态" width="80">
        <template slot-scope="{row}">
          {{PASSOPTIONSSTATUSLIST[row.call]}}
        </template>
      </el-table-column> -->
      <el-table-column label="客户标签" :width="80">
        <template slot-scope="{ row }">
          <el-tag
            v-for="(item, index) in getTagList(row.label)"
            class="tab_el_tag"
            size="mini"
            :key="index"
            >{{ item }}</el-tag
          >
        </template>
      </el-table-column>
      <!-- <el-table-column label="公共池" :width="80">
        <template slot-scope="{row}">
          <public-poll :id="row.publicPool" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="状态" :width="sortTdWidth">
        <template slot-scope="{row}">
          {{FIXTYPELIST[row.fit]}}
        </template>
      </el-table-column> -->
      <el-table-column prop="remark" label="条件备注" :width="longTdWidth">
        <template slot-scope="{ row }">
          <condition-remark :list="getTagList(row.remark, ';')" />
        </template>
      </el-table-column>
      <el-table-column label="跟进记录" :width="longTdWidth">
        <template slot-scope="scope">
          <el-popover placement="left-end" trigger="hover" width="500">
            <div class="remarkBox">
              <div class="remarkList">
                <div
                  class="item mb-3"
                  v-for="(item, index) in scope.row.remarkList"
                  :key="index"
                >
                  <div class="remark">{{ item.remark }}</div>
                  <div class="createBy pl-3">{{ item.createBy }}</div>
                  <div class="updateDate ml-3">{{ item.updateDate }}</div>
                </div>
              </div>
            </div>
            <div class="remarkList" slot="reference">
              <div
                class="item"
                :class="{ hide: index > 2 }"
                v-for="(item, index) in scope.row.remarkList"
                :key="index"
              >
                <div class="remark">{{ cutWordLength(item.remark, "17") }}</div>
                <div class="createBy pl-3">{{ item.createBy }}</div>
                <div class="updateDate ml-3">{{ item.updateDate }}</div>
              </div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="未跟进" :width="tdWidth">
        <template slot-scope="scope">
          <div class="red">{{ scope.row.days || "—" }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createDate" label="最后备注日期" :width="tdWidth" />
      <el-table-column prop="createDate" label="入库时间" :width="tdWidth" />
      <el-table-column prop="distributeDate" label="分配日期" :width="tdWidth" /> -->
      <el-table-column
        prop="remarkDate"
        label="最后备注日期"
        sortable="remark_date"
        :width="tdWidth"
      >
        <template slot-scope="{ row }">
          {{ row.remarkDate || "—" }}
        </template>
      </el-table-column>

      <el-table-column
        prop="createDate"
        label="入库时间"
        sortable="create_date"
        :width="tdWidth"
      >
        <template slot-scope="{ row }">{{ row.createDate || "—" }}</template>
      </el-table-column>
      <el-table-column
        prop="distributeDate"
        label="分配时间"
        sortable="distribute_date"
        :width="tdWidth"
      >
        <template slot-scope="{ row }">{{
          row.distributeDate || "—"
        }}</template>
      </el-table-column>
      <el-table-column width="100" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            plain
            @click="followUpHandle(scope.row)"
            >跟进</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <BasePagination
      v-model="page"
      :total="totalCount"
      :pageSize="pageSize"
      @change="pageOnChange"
    />
    <el-dialog
      title="协助"
      width="30%"
      :visible.sync="chooseDialogVisi"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="选择协助人">
          <el-select
            v-model="helpEmployeeId"
            clearable
            placeholder="选择协助人"
          >
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chooseDialogVisi = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="assistSubmitLoading"
          @click="assistSubmit"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <!-- 跟进弹框 开始 -->
    <glsx-dialog
      title="跟进"
      width="60%"
      :show="dialogFormVisible"
      @close="closeDialog()"
    >
      <follow-up
        ref="followUpCom"
        v-if="dialogFormVisible"
        :data="selectItem"
        @change="onChange"
      ></follow-up>
      <div slot="footer">
        <el-button
          type="primary"
          size="small"
          :loading="updateLoading"
          @click="updateCustomer()"
          >保存</el-button
        >
        <el-button type="default" size="small" @click="closeDialog()"
          >取消</el-button
        >
      </div>
    </glsx-dialog>
    <!-- 跟进弹框 end -->
  </div>
</template>

<script>
// import Params from "./Params.vue";
import Params from "@/components/common/params.vue";
import {
  newCustomerList,
  cancleHelp,
  employeeList,
  helpCustomer,
  UPLOADFILEPATH,
} from "@/api/customer";
import {
  followUpOptions,
  startOptions,
  passOptions,
  effectiveOptions,
} from "./config";
import { mapState } from "vuex";
import {
  FIXTYPELIST,
  PASSOPTIONSSTATUSLIST,
  SEXTYPELIST,
} from "@/common/constants";
import GlsxDialog from "@/components/Dialog";
import FollowUp from "@/components/follow";
import TabUser from "@/components/user";
import {
  showFollowProcess,
  getTagList,
  received,
  broadcast,
} from "@/utils/util";
export default {
  components: { Params, GlsxDialog, FollowUp, TabUser },
  data() {
    return {
      fieldList: [],
      page: 1,
      pageSize: 100,
      dataList: [],
      totalCount: 0,
      dialogFormVisible: false,
      form: {},
      followUpOptions: this.$store.state.common.followStatus,
      startOptions,
      passOptions,
      effectiveOptions,
      value1: "",
      selectItem: {},
      input: "",
      assistLoading: false,
      assistDisabled: true,
      chooseDialogVisi: false,
      updateLoading: false,
      employeeList: [],
      helpEmployeeId: "",
      assistSubmitLoading: false,
      formSize: "small",
      sortTdWidth: 56,
      smallWidth: 110,
      tdWidth: 160,
      longTdWidth: 500,
      UPLOADFILEPATH: UPLOADFILEPATH,
      idcardFront: "",
      idcardBack: "",
      authorizeFile: "",
      creditFile: "",
      otherFile: [],
      FIXTYPELIST: FIXTYPELIST,
      PASSOPTIONSSTATUSLIST,
      SEXTYPELIST,
      showFollowProcess: (str) => showFollowProcess(str),
      getTagList: (str, id) => getTagList(str, id),
      loading: false,
      tableHeight: 0,
    };
  },
  computed: {
    ...mapState({
      fieldList1: (state) => state.myClient.fieldList,
    }),
  },
  mounted() {
    console.log(this.$store.state.common.followStatus);
    this.fieldList = JSON.parse(JSON.stringify(this.fieldList1));
    received("update.success", this.newCustomerList);

    // 计算表格的高度
    let _this = this;
    this.$getTableHeight();
    window.onresize = function () {
      _this.$getTableHeight();
    };
  },
  watch: {
    fieldList1(val) {
      this.fieldList = JSON.parse(JSON.stringify(val));
    },
  },
  methods: {
    // async callPhone(item) {
    //   const { id, mobile } = item
    //   const parmas = {
    //     customerId: id,
    //     mobile
    //   }
    //   const res = await call(parmas)
    //   if (!res.result) return
    //   this.$confirm(res.message, '提示', {
    //     confirmButtonText: '已拨通',
    //     cancelButtonText: '取消',
    //     type: 'success'
    //   })
    //     .then(() => {})
    //     .catch(() => {})
    // },
    async newCustomerList(form) {
      this.showAppLoading();
      try {
        this.loading = true;
        await newCustomerList({
          page: this.page,
          size: this.pageSize,
          paramObject: { ...form },
        }).then((res) => {
          this.loading = false;
          const { data } = res;
          this.dataList = data.dataList || [];
          this.totalCount = data.totalCount;
          this.dataList.forEach((element) => {
            if (element.id === this.selectItem.id) {
              this.selectItem = element;
            }
          });
          this.$nextTick(() => {
            let index = 0;
            const list = document.querySelectorAll("tr");
            const tbody = document.querySelector("tbody");
            const comment = tbody.getElementsByClassName("comment");
            for (let index1 = comment.length - 1; index1 >= 0; index1--) {
              const element = comment[index1];
              element.remove();
            }
            list.forEach((dom) => {
              if (dom.classList.contains("el-table__row")) {
                if (this.dataList[index] && this.dataList[index].comment) {
                  const div = document.createElement("div");
                  div.innerHTML = `主管点评：${this.dataList[index].comment}`;
                  div.classList.add("comment");
                  dom.parentNode.insertBefore(div, dom);
                }
                index++;
              }
            });
          });
        });
        this.hideAppLoading();
      } catch (error) {
        this.hideAppLoading();
      }
    },
    pageOnChange(row) {
      this.page = row.page;
      if (row.pageSize) {
        this.pageSize = row.pageSize;
      }
      this.$refs.params.search();
    },
    addCustomerHandle() {
      this.$router.push({ name: "addClient" });
    },
    followUpHandle(item) {
      const arr = [];
      if (item.otherFile) {
        item.otherFile.split(",").map((k) => {
          arr.push({ name: k, url: k });
        });
      }
      //this.otherFile = arr;
      let selectItem = Object.assign({}, item);
      // this.value1 = item.appointmentDate;
      // this.dialogFormVisible = true;
      broadcast("look.user.follow", { data: selectItem, list: this.dataList });
    },
    handleSelectionChange(e) {
      this.assistDisabled = e.length === 0;
      this.idArr = e.map((element) => element.id);
    },
    onSubmit() {},
    async assistHandle() {
      employeeList().then((res) => {
        this.employeeList = res.data;
      });
      this.chooseDialogVisi = true;
    },
    async assistSubmit() {
      this.assistSubmitLoading = true;
      try {
        await helpCustomer({
          idList: this.idArr,
          helpEmployeeId: this.helpEmployeeId,
        }).then((res) => {
          this.$message.success(res.message);
          this.chooseDialogVisi = false;
        });
        this.assistSubmitLoading = false;
      } catch (error) {
        this.assistSubmitLoading = false;
      }
    },
    cancleAssistHandle() {
      this.$confirm("确认取消协助?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "删除中...";
            try {
              await cancleHelp({ idList: this.idArr }).then((res) => {});
              done();
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
            } catch (error) {
              done();
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
            }
          } else {
            done();
          }
        },
      });
    },
    updateCustomer() {
      // 编辑客户
      this.updateLoading = true;
      this.$refs.followUpCom.saveInfo();
      // const { progress, id, level, remark, call, fit } = this.selectItem;
      // const form = { progress, id, level, remark, call, fit };
      // if (this.value1) {
      //   // 预约上门时间
      //   form.appointmentDate = this.value1;
      // }
      // for (const key in this.selectItem) {
      //   if (Object.hasOwnProperty.call(this.selectItem, key)) {
      //     if (key.indexOf("field") > -1) {
      //       form[key] = this.selectItem[key];
      //     }
      //   }
      // }
      // if (this.input) {
      //   form.customerRemark = { remark: this.input };
      // }

      // try {
      //   await updateCustomer(form).then((res) => {
      //     this.$refs.params.search();
      //     this.$message.success(res.message);
      //     this.input = "";
      //   });
      //   this.updateLoading = false;
      // } catch (error) {
      //   this.updateLoading = false;
      // }
    },

    // 关闭弹框
    closeDialog() {
      this.dialogFormVisible = false;
      this.newCustomerList();
    },

    // 监听组件变化
    onChange(e) {
      this.updateLoading = false;
      if (e) {
        this.closeDialog();
      }
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      console.log(column);
      //this.formInline.orderField = prop;
      let str = `${column.sortable} asc`;
      if (order == "ascending") {
        str = `${column.sortable} asc`;
      } else {
        str = `${column.sortable} desc`;
      }
      this.$refs.params.setParams("sort", str);
      this.$refs.params.search();
      //this.getList();
    },
  },
};
</script>

<style>
.NewCustomer {
  padding: 20px;
}
.txt {
  padding: 8px 0;
}
.wrapping {
  margin-right: 10px;
  margin-bottom: 10px;
}
.btn {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}
</style>
<style lang="scss" scoped>
.upload_box {
  display: flex;
  align-items: center;
  .avatar-uploader {
    margin: 0 16px 0 0;
    ::v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      height: 120px;
      width: 120px;
    }
    .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      // width: 120px;
      // height: 120px;
      // line-height: 120px;
      text-align: center;
    }
    .avatar {
      width: 100%;
      height: 100%;
      display: block;
    }
    .upload_tips {
      height: 100%;
      display: flex;
      flex-direction: column;
      font-size: 12px;
      color: #999;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
